<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\common\model\groupon;

use cores\BaseModel;
use think\facade\Cache;
use app\common\library\helper;
use app\common\enum\DiscountType as DiscountTypeEnum;

/**
 * 拼团活动设置模型
 * Class Setting
 * @package app\common\model\groupon
 */
class Setting extends BaseModel
{
    // 定义表名
    protected $name = 'groupon_setting';

    protected $createTime = false;

    /**
     * 获取器: 转义数组格式
     * @param $value
     * @return array
     */
    public function getValuesAttr($value): array
    {
        return helper::jsonDecode($value);
    }

    /**
     * 修改器: 转义成json格式
     * @param $value
     * @return string
     */
    public function setValuesAttr($value): string
    {
        return helper::jsonEncode($value);
    }

    /**
     * 获取是否开启分销
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getIsDealer()
    {
        return static::getItem('basic')['isDealer'];
    }

    /**
     * 获取是否开启分销
     * @param string $value
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function existDiscount(string $value): bool
    {
        $otherDiscount = static::getItem('basic')['otherDiscount'];
        return in_array($value, $otherDiscount);
    }

    /**
     * 获取指定项设置
     * @param string $key
     * @param int|null $storeId
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getItem(string $key, int $storeId = null)
    {
        $data = static::getAll($storeId);
        return isset($data[$key]) ? $data[$key]['values'] : [];
    }

    /**
     * 获取全部设置
     * @param int|null $storeId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAll(int $storeId = null): array
    {
        $model = new static;
        is_null($storeId) && $storeId = $model::$storeId;
        if (!$data = Cache::get("groupon_setting_{$storeId}")) {
            // 获取全部设置
            $setting = $model->getList($storeId);
            $data = $setting->isEmpty() ? [] : helper::arrayColumn2Key($setting->toArray(), 'key');
            // 写入缓存中
            Cache::tag('cache')->set("groupon_setting_{$storeId}", $data);
        }
        // 重组setting缓存数据 (多维)
        return static::reorganize($model->defaultData(), $data, $type = 'cache');
    }

    /**
     * 获取设置列表
     * @param int $storeId
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getList(int $storeId): \think\Collection
    {
        return $this->where('store_id', '=', $storeId)->select();
    }

    /**
     * 获取设置项信息
     * @param string $key
     * @return static|array|null
     */
    public static function detail(string $key)
    {
        return static::get(compact('key'));
    }

    /**
     * 默认配置
     * @return array
     */
    public function defaultData(): array
    {
        return [
            'basic' => [
                'key' => 'basic',
                'describe' => '基础设置',
                'values' => [
                    // 拼单失败自动退款
                    'taskFailAutoRefund' => false,
                    // 拼团活动是否参与分销
                    'isDealer' => false,
                    // 是否叠加其他优惠方式
                    'isOtherDiscount' => false,
                    // 可叠加的其他优惠方式：优惠券、积分抵扣
                    'otherDiscount' => [DiscountTypeEnum::COUPON, DiscountTypeEnum::POINTS],
                    // 拼团活动图
                    'backdrop' => ['src' => base_url() . 'assets/store/img/groupon/backdrop.png'],
                    // 拼团规则: 简述
                    'ruleBrief' => '好友拼单 · 人满发货 · 人不满退款',
                    // 拼团规则: 详述
                    'ruleDetail' => "开团：选择商品，点击“发起拼单”按钮，付款完成后即开团成功，就可以邀请小伙伴一起拼团啦;\n\n参团：进入朋友分享的页面，点击“立即参团”按钮，付款完成后参团成功，在有效时间内凑齐人数即成团，就可以等待收货喽;\n\n成团：在开团或参团成功后，点击“立即分享”将页面分享给好友，在有效时间内凑齐人数即成团，成团后商家开始发货;\n\n组团失败：在有效时间内未凑齐人数，即组团失败，组团失败后订单所付款将原路退回到支付账户。",
                ]
            ]
        ];
    }

    /**
     * 是否开启拼单失败自动退款
     * @param int|null $storeId
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function taskFailAutoRefund(int $storeId = null): bool
    {
        return (bool)static::getItem('basic', $storeId)['taskFailAutoRefund'];
    }
}